package com.lenin.omena.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.maps.client.MapPane;
import com.google.gwt.maps.client.geom.Point;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.Widget;
import com.lenin.omena.client.event.ProduceListChangeEvent;
import com.lenin.omena.client.event.ProduceListChangeEventHandler;
import com.lenin.omena.shared.domain.Produce;
import com.lenin.omena.shared.domain.Site;
import com.lenin.omena.shared.domain.User;
import com.lenin.omena.shared.domain.UserInfo;

public class MarkerPanel extends Composite implements ProduceListChangeEventHandler {

	
	interface MyUiBinder extends UiBinder<Widget, MarkerPanel> {
	}
	
	private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

	public enum State {
		CLOSED, OPEN;
	}

	@UiField
	HTMLPanel containerPanel;

	@UiField
	HTMLPanel contentPanel;

	private AbsolutePanel parentPanel;
	private FocusPanel focusPanel;
	
	private Point locationPoint;
	private MapPane pane;

	private int width = 100;
	private int height = 100;

	private String text;

	private State state = State.CLOSED;

	private User owner;
	//private List<Produce> produce;
	
	private Grid grid;
	private FlexTable contentsTable;
	
	public MarkerPanel(AbsolutePanel parentPanel, User user) {

		initWidget(uiBinder.createAndBindUi(this));
		
		this.parentPanel = parentPanel;
		
		owner = user;
		
		ProduceListChangeEvent.register(AppleMarket.getEventBus(), this);
		
		generateContentTables(user);
		
		focusPanel = new FocusPanel();
		focusPanel.getElement().getStyle().setZIndex(3000);
		focusPanel.getElement().getStyle().setPropertyPx("outline", 0);
		//focusPanel.getElement().getStyle().setProperty("backgroundColor", "red");

		setWidth(width);
		setHeight(height);

		setText(text);

	}

	
	private void generateContentTables(User user) {
		
		boolean addGrid = false;
		boolean addContents = false;
		
		if(grid != null) {
			addGrid = contentPanel.remove(grid);
		} else {
			addGrid = true;
		}
		
		if(contentsTable != null) {
			addContents = contentPanel.remove(contentsTable);
		} else {
			addContents = true;
		}
		
		UserInfo userInfo = user.getUserInfo();

		contentsTable = new FlexTable();
		contentsTable.setStyleName("expandedMarkerTable");

		contentsTable.setHTML(0, 0,
				"<b>Yhteystiedot</b> (" + userInfo.getUserName() + ")");
		contentsTable.getRowFormatter().setStyleName(0,
				"expandedMarkerHeaderRow");
		contentsTable.getFlexCellFormatter().setColSpan(0, 0, 3);

		contentsTable.setHTML(1, 0, "Sähköposti: <i>" + userInfo.getEmail()
				+ "</i>");
		contentsTable.getFlexCellFormatter().setColSpan(1, 0, 3);

		contentsTable.setHTML(2, 0, "Puhelin: <i>" + userInfo.getPhoneNumber()
				+ "</i>");
		contentsTable.getFlexCellFormatter().setColSpan(2, 0, 3);
		if (userInfo.getPhoneNumber() == null)
			contentsTable.getRowFormatter().setVisible(2, false);

		contentsTable.setHTML(3, 0, "<br />");

		contentsTable.setHTML(4, 0, "<b>Tarjottavat tuotteet</b>");
		contentsTable.getFlexCellFormatter().setColSpan(4, 0, 3);

		int rowNum = 5;

		List<String> prNames = new ArrayList<String>();
		Site site = user.getSite();
		if (site.getProduce() != null) {
			List<Produce> produce = site.getProduce();
			for (Produce p : produce) {

				String prName = p.getName().toLowerCase();
				if (!prNames.contains(prName)) {
					prNames.add(prName);
				}

				contentsTable.setHTML(rowNum, 0, AppleMarket.forXML(p.getName()));
				contentsTable.setHTML(rowNum, 1, AppleMarket.forXML(p.getAmount()));
				contentsTable.setHTML(rowNum, 2, AppleMarket.forXML(p.getPrice()));
				contentsTable.getCellFormatter().setAlignment(rowNum, 2,
						HasHorizontalAlignment.ALIGN_RIGHT,
						HasVerticalAlignment.ALIGN_MIDDLE);

				rowNum++;

			}
		}

		int prCount = prNames.size();

		if (prCount == 0) {

			grid = new Grid(1, 1);
			grid.setHTML(0, 0, " ");
			setCellBackground(grid.getCellFormatter().getElement(0, 0),
					getImageFile("question", "40x40"), "100%");

		} else if (prCount == 1) {

			grid = new Grid(1, 1);
			grid.setHTML(0, 0, " ");
			setCellBackground(grid.getCellFormatter().getElement(0, 0),
					getImageFile(prNames.get(0), "40x40"), "100%");

		} else if (prCount == 2) {

			grid = new Grid(1, 2);

			grid.setHTML(0, 0, " ");
			setCellBackground(grid.getCellFormatter().getElement(0, 0),
					getImageFile(prNames.get(0), "20x20"), "50%");

			grid.setHTML(0, 1, " ");
			setCellBackground(grid.getCellFormatter().getElement(0, 1),
					getImageFile(prNames.get(1), "20x20"), "50%");

		} else if (prCount == 3) {

			grid = new Grid(2, 1);
			grid.getCellFormatter().setStyleName(1, 0, "markerTableColspan");
			Grid grid2 = new Grid(1, 2);
			grid.setWidget(1, 0, grid2);

			grid.setHTML(0, 0, " ");
			setCellBackground(grid.getCellFormatter().getElement(0, 0),
					getImageFile(prNames.get(0), "20x20"), "100%");

			grid2.setHTML(0, 0, " ");
			setCellBackground(grid2.getCellFormatter().getElement(0, 0),
					getImageFile(prNames.get(1), "20x20"), "50%");

			grid2.setHTML(0, 1, " ");
			setCellBackground(grid2.getCellFormatter().getElement(0, 1),
					getImageFile(prNames.get(2), "20x20"), "50%");

			grid2.setStyleName("markerTable");

		} else {

			grid = new Grid(2, 2);

			grid.setHTML(0, 0, " ");
			setCellBackground(grid.getCellFormatter().getElement(0, 0),
					getImageFile(prNames.get(0), "20x20"), "50%");

			grid.setHTML(0, 1, " ");
			setCellBackground(grid.getCellFormatter().getElement(0, 1),
					getImageFile(prNames.get(1), "20x20"), "50%");

			grid.setHTML(1, 0, " ");
			setCellBackground(grid.getCellFormatter().getElement(1, 0),
					getImageFile(prNames.get(2), "20x20"), "50%");

			grid.setHTML(1, 1, " ");
			setCellBackground(grid.getCellFormatter().getElement(1, 1),
					getImageFile(prNames.get(3), "20x20"), "50%");

		}

		grid.setStyleName("markerTable");
		
		
		if(addGrid && addContents) {
			
			contentPanel.add(grid);
			
		} else {
			
			if(addGrid) {
				contentPanel.add(grid);
			} else  {
				contentPanel.add(contentsTable);
			}
			
		}
		
		
	}
	
	
	private String getImageFile(String produceName, String size) {

		String fileName = "star";

		if (produceName.contains("question")) {
			fileName = "question";
		} else if (produceName.contains("omen") || produceName.contains("apple")) {
			fileName = "apple";
		} else if (produceName.contains("luum") || produceName.contains("plum")) {
			fileName = "plum";
		} else if (produceName.contains("kirsik")
				|| produceName.contains("cherr")) {
			fileName = "cherry";
		} else if (produceName.contains("mansik")
				|| produceName.contains("strawb")) {
			fileName = "strawberry";
		}

		fileName += "-icon-" + size + ".png";

		return fileName;

	}

	private void setCellBackground(Element cellElement, String imageFile, String width) {

		cellElement.getStyle().setProperty("background", 
				"url('" + imageFile+ "') no-repeat scroll center transparent");
		cellElement.getStyle().setProperty("width", width);

	}

	public void initialize(MapPane pane) {

		this.pane = pane;
		//pane.add(focusPanel);
		parentPanel.add(focusPanel);
		
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {

		this.text = text;

	}

	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}

	public int getWidth() {
		return width;
	}

	private void setWidth(int width) {
		this.width = width;
		containerPanel.setWidth(width + "px");
		contentPanel.setHeight((height - 46) + "px");
		focusPanel.setWidth((width - 46) + "px");
	}

	public int getHeight() {
		return height;
	}

	private void setHeight(int height) {
		this.height = height;
		containerPanel.setHeight(height + "px");
		contentPanel.setHeight((height - 46) + "px");
		focusPanel.setHeight((height - 46) + "px");
	}

	public Point getLocation() {
		return locationPoint;
	}

	
	public void setLocation(Point locationPoint) {

		this.locationPoint = locationPoint;
		
		int left = locationPoint.getX() - (width / 2);
		int top = locationPoint.getY() - (height - 17);
		
		pane.setWidgetPosition(this, left, top);
		//pane.setWidgetPosition(focusPanel, left + 23, top + 23);
		parentPanel.setWidgetPosition(focusPanel, getAbsoluteLeft() + 23, getAbsoluteTop() + 23);
		
	}

	
	public void setSize(int width, int height) {

		setWidth(width);
		setHeight(height);

		int left = locationPoint.getX() - (width / 2);
		int top = locationPoint.getY() - (height - 17);

		pane.setWidgetPosition(this, left, top);
		//pane.setWidgetPosition(focusPanel, left + 23, top + 23);
		parentPanel.setWidgetPosition(focusPanel, getAbsoluteLeft() + 23, getAbsoluteTop() + 23);
		
		
	}

	public void expand() {

		contentPanel.remove(grid);
		contentPanel.add(contentsTable);

		setSize(300, 300);

		setState(State.OPEN);

	}

	public void shrink() {

		contentPanel.remove(contentsTable);
		contentPanel.add(grid);

		setSize(100, 100);

		setState(State.CLOSED);

	}

	public void addMouseUpHandler(MouseUpHandler handler) {
		focusPanel.addMouseUpHandler(handler);
	}

	@Override
	public void onProduceListChange(ProduceListChangeEvent event) {
		
		User user = AppleMarket.getUserContext().getUser();
		
		if(user != null && user.getKey().equals(owner.getKey())) {
			owner = user;
			generateContentTables(user);
		}

	}

}
